from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from webdriver_manager.chrome import ChromeDriverManager
import time


class YuketangAuto:
    def __init__(self):
        """初始化浏览器 - 自动管理ChromeDriver"""
        print("🚀 初始化浏览器...")

        try:
            options = webdriver.ChromeOptions()
            # 禁用自动化提示
            options.add_experimental_option('excludeSwitches', ['enable-automation'])
            options.add_experimental_option('useAutomationExtension', False)

            # 自动下载并使用ChromeDriver
            print("📥 自动配置ChromeDriver...")
            service = Service(ChromeDriverManager().install())

            self.driver = webdriver.Chrome(service=service, options=options)
            self.driver.maximize_window()
            self.wait = WebDriverWait(self.driver, 30)

            print("✅ 浏览器初始化完成")

        except Exception as e:
            print(f"❌ 初始化失败: {e}")
            print("\n可能的解决方案:")
            print("1. 检查Chrome浏览器是否已安装")
            print("2. 尝试运行: pip install --upgrade selenium webdriver-manager")
            raise

    def login(self, url):
        """打开登录页面，等待手动登录"""
        print(f"\n📖 打开页面: {url}")
        self.driver.get(url)

        print("\n⚠️  请手动登录...")
        print("登录完成后，按回车键继续...")
        input()

        print("✅ 登录确认完成")

    def should_skip_title(self, title):
        """判断是否应该跳过该标题"""
        skip_keywords = ['作业', '练习', '测验', '考试', '试卷', '问卷']
        for keyword in skip_keywords:
            if keyword in title:
                return True
        return False

    def get_iframe_doc(self):
        """切换到iframe"""
        try:
            iframe = self.wait.until(
                EC.presence_of_element_located((By.TAG_NAME, "iframe"))
            )
            self.driver.switch_to.frame(iframe)
            return True
        except TimeoutException:
            print("❌ 未找到iframe")
            return False

    def find_next_video(self):
        """在列表页查找下一个未完成的视频"""
        print("\n" + "=" * 50)
        print("🔍 [列表页] 查找未完成视频...")

        # 切换到iframe
        self.driver.switch_to.default_content()

        if not self.get_iframe_doc():
            return False

        time.sleep(2)

        try:
            chapters = self.driver.find_elements(By.CLASS_NAME, "chapter-list")
            print(f"📚 找到 {len(chapters)} 个章节")

            if len(chapters) == 0:
                print("❌ 未找到章节")
                self.driver.switch_to.default_content()
                return False

            for chapter_idx, chapter in enumerate(chapters, 1):
                sections = chapter.find_elements(By.CLASS_NAME, "section-list")

                for section_idx, section in enumerate(sections, 1):
                    try:
                        content = section.find_element(By.CLASS_NAME, "content")

                        # 检查是否已完成
                        try:
                            progress_wrap = content.find_element(By.CLASS_NAME, "progress-wrap")
                            if "已完成" in progress_wrap.text:
                                print(f"⏭️  章节{chapter_idx}-{section_idx}: 已完成，跳过")
                                continue
                        except NoSuchElementException:
                            pass

                        # 查找标题
                        try:
                            title_span = content.find_element(By.CSS_SELECTOR, "span.title")
                            title = title_span.text.strip()

                            if self.should_skip_title(title):
                                print(f"⏭️  章节{chapter_idx}-{section_idx}: {title} (作业/练习，跳过)")
                                continue

                            print(f"✅ 找到视频: {title}")
                            print(f"🎬 点击进入...")

                            title_span.click()
                            self.driver.switch_to.default_content()
                            return True

                        except NoSuchElementException:
                            continue

                    except NoSuchElementException:
                        continue

            print("\n🎉 所有视频已完成！")
            self.driver.switch_to.default_content()
            return False

        except Exception as e:
            print(f"❌ 查找视频时出错: {e}")
            self.driver.switch_to.default_content()
            return False

    def play_video(self):
        """在播放页播放视频"""
        print("\n" + "=" * 50)
        print("▶️  [播放页] 开始处理...")

        time.sleep(5)

        try:
            print("🔍 查找video元素...")
            video = self.wait.until(
                EC.presence_of_element_located((By.TAG_NAME, "video"))
            )
            print("✅ 找到video元素")

            print("▶️  开始播放视频...")

            # 静音播放
            self.driver.execute_script("arguments[0].muted = true;", video)
            self.driver.execute_script("arguments[0].play();", video)

            time.sleep(1)
            self.driver.execute_script("arguments[0].muted = false;", video)

            print("✅ 视频播放成功")

            self.monitor_video_progress()

            return True

        except TimeoutException:
            print("⚠️  未找到video元素，可能是作业页面")
            print("🔙 点击返回...")
            self.click_back()
            return False
        except Exception as e:
            print(f"❌ 播放视频时出错: {e}")
            return False

    def monitor_video_progress(self):
        """监控视频播放进度"""
        print("\n👀 开始监控视频进度...")

        check_count = 0
        max_checks = 2000

        while check_count < max_checks:
            time.sleep(3)
            check_count += 1

            try:
                video = self.driver.find_element(By.TAG_NAME, "video")

                current_time = self.driver.execute_script("return arguments[0].currentTime;", video)
                duration = self.driver.execute_script("return arguments[0].duration;", video)
                paused = self.driver.execute_script("return arguments[0].paused;", video)

                if check_count % 10 == 0:
                    current_min = int(current_time // 60)
                    current_sec = int(current_time % 60)
                    total_min = int(duration // 60)
                    total_sec = int(duration % 60)

                    print(
                        f"⏱️  进度: {current_min}:{current_sec:02d} / {total_min}:{total_sec:02d} - 播放中: {not paused}")

                if paused and current_time > 0:
                    print("⚠️  视频暂停了，尝试继续播放")
                    self.driver.execute_script("arguments[0].play();", video)

                try:
                    progress_wrap = self.driver.find_element(By.CLASS_NAME, "progress-wrap")
                    if "已完成" in progress_wrap.text:
                        print("\n✅ 视频播放完成！")
                        time.sleep(2)
                        self.click_back()
                        return
                except NoSuchElementException:
                    pass

            except NoSuchElementException:
                print("❌ video元素消失")
                return
            except Exception as e:
                print(f"❌ 监控时出错: {e}")
                return

        print("⚠️  监控超时")

    def click_back(self):
        """点击返回按钮"""
        print("\n🔙 [返回] 点击返回按钮...")

        try:
            back_button = self.driver.find_element(By.CLASS_NAME, "back")
            back_button.click()
            print("✅ 已点击返回")
            time.sleep(5)
        except NoSuchElementException:
            print("⚠️  未找到返回按钮，使用浏览器返回")
            self.driver.back()
            time.sleep(5)

    def run(self, course_url, max_videos=100):
        """主循环：自动刷课"""
        self.login(course_url)

        print("\n" + "=" * 50)
        print("🎬 开始自动刷课...")
        print("=" * 50)

        videos_processed = 0

        while videos_processed < max_videos:
            if self.find_next_video():
                self.play_video()
                videos_processed += 1
                print(f"\n📊 已完成 {videos_processed} 个视频")
            else:
                print("\n✅ 所有视频已完成！")
                break

            time.sleep(2)

        print("\n" + "=" * 50)
        print(f"🎉 刷课完成！共处理 {videos_processed} 个视频")
        print("=" * 50)

    def close(self):
        """关闭浏览器"""
        print("\n👋 关闭浏览器...")
        self.driver.quit()


if __name__ == "__main__":
    # ========== 配置区域 ==========

    # 课程列表页URL（修改为你的课程URL）
    COURSE_URL = "https://www.yuketang.cn/v2/web/studentLog/12345678?university_id=1234&platform_id=1234&classroom_id=12345678&content_url="

    # 最多处理多少个视频
    MAX_VIDEOS = 100

    # ==============================

    try:
        auto = YuketangAuto()
        auto.run(COURSE_URL, MAX_VIDEOS)

        print("\n按回车键退出...")
        input()

    except KeyboardInterrupt:
        print("\n\n⚠️  用户中断")
    except Exception as e:
        print(f"\n❌ 发生错误: {e}")
        import traceback

        traceback.print_exc()
    finally:
        try:
            auto.close()
        except:
            pass